## scheduler.py
import time
from apscheduler.schedulers.background import BackgroundScheduler
from fetcher import Fetcher
from translator import Translator
from webhook_sender import WebhookSender
import logging

class Scheduler:
    def __init__(self, fetch_interval: int = 24, keywords: list[str] = None, target_language: str = 'zh', webhook_url: str = ''):
        """
        Initializes the Scheduler with default settings.

        :param fetch_interval: Interval in hours between fetches.
        :param keywords: List of keywords for filtering papers.
        :param target_language: Target language for translation.
        :param webhook_url: Webhook URL for sending notifications.
        """
        self.scheduler = BackgroundScheduler()
        self.fetcher = Fetcher()
        self.translator = Translator()
        self.webhook_sender = WebhookSender()
        self.fetch_interval = fetch_interval
        self.keywords = keywords if keywords is not None else ['deep learning', 'machine learning']
        self.target_language = target_language
        self.webhook_url = webhook_url
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

    def schedule_fetching(self):
        """
        Schedules the fetching, translation, and notification tasks.
        """
        self.scheduler.add_job(self._execute_task, 'interval', hours=self.fetch_interval)

    def _execute_task(self):
        """
        Executes the scheduled task with error handling and retry logic.
        """
        abstracts = self.fetcher.fetch_abstracts(self.keywords)
        if not abstracts:
            logging.error("Failed to fetch abstracts. Will retry in the next cycle.")
            return

        for abstract in abstracts:
            translated_text = self._safe_translate(abstract)
            if translated_text:
                self._safe_send_to_dingtalk(translated_text)

    def _safe_translate(self, text):
        try:
            return self.translator.translate(text, self.target_language)
        except Exception as e:
            logging.error(f"Translation failed with error: {e}")
            return None

    def _safe_send_to_dingtalk(self, message):
        try:
            self.webhook_sender.send_to_dingtalk(message, self.webhook_url)
        except Exception as e:
            logging.error(f"Sending to DingTalk failed with error: {e}")

    def start(self):
        """
        Starts the scheduler.
        """
        self.schedule_fetching()
        self.scheduler.start()
        logging.info("Scheduler started.")

    def stop(self):
        """
        Stops the scheduler.
        """
        self.scheduler.shutdown()
        logging.info("Scheduler stopped.")

if __name__ == "__main__":
    scheduler = Scheduler(webhook_url="Your_DingTalk_Webhook_URL")
    try:
        scheduler.start()
        # Keep the script running
        while True:
            time.sleep(1)
    except (KeyboardInterrupt, SystemExit):
        scheduler.stop()
